package com.sqsf.util;

import com.sqsf.javabean.User;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;

public class UserMapperTest {
    private SqlSession session;
    private UserMapper mapper;

    @Before
    public void before() {
        // 创建SqlSessionFactory对象
        SqlSessionFactory factory = MyBatisUtil.getSqlSessionFactory();
        // 创建SqlSession对象，true表示自动提交事务
        session = factory.openSession(true);
        // 获取Mapper接口的代理对象
        mapper = session.getMapper(UserMapper.class);
    }

    @After
    public void after() {
        // 关闭资源
        if(session != null) {
            session.close();
        }
    }

    @Test
    public void selectAll() {
        List<User> users = mapper.selectAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testDynamicSQL() {

        User condition = new User();
        condition.setUsername("a");

        List<User> users = mapper.selectByCondition(condition);
        System.out.println("=== 按用户名模糊查询 ===");
        for (User user : users) {
            System.out.println(user);
        }


        condition = new User();
        condition.setUsername("a");
        condition.setPhone("a");

        users = mapper.selectByCondition(condition);
        System.out.println("\n=== 按用户名和电话号码查询 ===");
        for (User user : users) {
            System.out.println(user);
        }


        condition = new User();
        users = mapper.selectByCondition(condition);
        System.out.println("\n=== 无条件查询（返回所有） ===");
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testUserWithRole() {

        User user = mapper.getUserWithRole("1");  // 查询ID为1的用户及其角色信息
        System.out.println("=== 用户及其角色信息 ===");
        System.out.println(user);

        if (user != null && user.getR() != null) {
            System.out.println("\n详细信息：");
            System.out.println("用户ID: " + user.getUid());
            System.out.println("用户名: " + user.getUsername());
            System.out.println("角色ID: " + user.getR().getRid());
            System.out.println("角色名: " + user.getR().getName());
            System.out.println("角色描述: " + user.getR().getDesc());
        }


        User user2 = mapper.getUserWithRole("2");
        System.out.println("\n=== 测试可能没有角色的用户 ===");
        System.out.println(user2);
    }
}